package com.semidata.rtd.core.http.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpRequest;

public abstract class UrlMatcher {

	protected String url;
	protected Class<? extends HttpDispatchHandler> handlerClass;

	public UrlMatcher(String url) {
		this.url = url;
	}
	
	protected boolean match(HttpRequest request) {
		String requestUrl = request.getUri();
		int pos = requestUrl.indexOf("?");
		if (pos != -1)
			requestUrl = requestUrl.substring(0, pos);
		if (!requestUrl.endsWith("/"))
			requestUrl = requestUrl.concat("/");
		return url.equals(requestUrl);
	}
	
	protected abstract HttpDispatchHandler createHandler(ChannelHandlerContext ctx, HttpRequest request);

	public HttpDispatchHandler getDispatchHandler(ChannelHandlerContext ctx, HttpRequest request) {
		if (match(request))
			return createHandler(ctx, request);
		return null;
	}
}
